package org.jeecg.modules.scene.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.device.entity.DeviceInstance;
import org.jeecg.modules.device.service.IDeviceInstanceService;
import org.jeecg.modules.scene.entity.Scene;
import org.jeecg.modules.scene.mapper.SceneMapper;
import org.jeecg.modules.scene.service.ISceneSchemeService;
import org.jeecg.modules.scene.service.ISceneService;
import org.jeecg.modules.scene.vo.DeployConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 场景管理
 * @Author: jeecg-boot
 * @Date: 2020-06-04
 * @Version: V1.0
 */
@Slf4j
@Service
public class SceneServiceImpl extends ServiceImpl<SceneMapper, Scene> implements ISceneService {

    @Autowired
    private SceneMapper sceneMapper;
    @Autowired
    private ISceneSchemeService sceneSchemeService;
    @Autowired
    private IDeviceInstanceService instanceService;
    @Autowired
    private ISysBaseAPI baseAPI;

    @Override
    public DeployConfig buildDeploy(Scene scene) {

        DeployConfig deploy = new DeployConfig(scene, sceneSchemeService.schemeCountListBySceneId(scene.getId()));

        List<DeployConfig> deployConfigs = instanceService.listDeployDevice();

        deploy.setDeviceInstances(deployConfigs);

        return deploy;
    }

    @Override
    public Scene getCurrentScene(String id, String username) {
        Scene scene = new Scene();
        if (StringUtils.isBlank(id) || "undefined".equals(id)) {
            if(StringUtils.isNotBlank(username)) {
                final LoginUser user = baseAPI.getUserByName(username);
                List<Scene> list = this.lambdaQuery().eq(Scene::getSysOrgCode, user.getOrgCode()).list();
                if (list != null && list.size() > 0) {
                    scene = list.get(0);
                } else {
                    throw new RuntimeException("未找到当前登录用户所属场景数据");
                }
            }
        } else {
            scene = this.getById(id);
            if (scene == null) {
                throw new RuntimeException("未找到id为：" + id + "的场景");
            }
        }
        return scene;
    }

    /**
     * 更新模型配置
     *
     * @param deployConfig 部署配置
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateModelAttribute(DeployConfig deployConfig) {
        boolean b = false;
        // 保存场景配置
        Scene scene = new Scene();
        scene.setId(deployConfig.getId());
        scene.setModelAttribute(deployConfig.getSceneAttribute());
        log.info("保存场景配置>>>{}", scene.getModelAttribute());
        b = this.updateById(scene);
        // 保存设备配置
        List<DeployConfig> deviceConfigs = deployConfig.getDeviceInstances();

        List<DeviceInstance> deviceInstances = deviceConfigs.stream().map(config -> {
            DeviceInstance instance = new DeviceInstance();
            instance.setId(config.getId());
            instance.setModelAttribute(config.getDeviceAttribute());
            log.info("保存设备配置>>>{}", instance.getModelAttribute());
            return instance;
        }).collect(Collectors.toList());

        b = instanceService.updateBatchById(deviceInstances);
        return b;
    }
}
